package com.judge.pe.utils;

import android.util.Xml;

import com.judge.pe.bean.PE;

import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuzhifan on 2015/9/14.
 */
public class PullPEParser{
    /**
     * 解析xml文档到内存
     * @param is
     * @return
     * @throws Exception
     */
    public List<PE> parse(InputStream is) throws Exception{
        List<PE> pes = null;
        PE pe = null;

       XmlPullParser parser = Xml.newPullParser(); //由android.util.Xml创建一个XmlPullParser实例
        parser.setInput(is, "UTF-8");               //设置输入流 并指明编码方式

        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT){
            switch (eventType) {
                case XmlPullParser.START_DOCUMENT:
                    pes = new ArrayList<PE>();
                    break;
                case XmlPullParser.START_TAG:
                    if (parser.getName().equals("pe")) {
                        pe = new PE();
                    } else if (parser.getName().equals("pname")) {
                        eventType = parser.next();
                        pe.pname = parser.getText();
                    } else if (parser.getName().equals("time")) {
                        eventType = parser.next();
                        pe.time = parser.getText();
                    } else if (parser.getName().equals("tools")) {
                        eventType = parser.next();
                        pe.tools = parser.getText();
                    }else if(parser.getName().equals("introduction")){
                        pe.introduction = parser.getText();
                    }else if(parser.getName().equals("summary")){
                        pe.summary = parser.getText();
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (parser.getName().equals("pe")) {
                        pes.add(pe);
                        pe = null;
                    }
                    break;
            }
            eventType = parser.next();
        }
        return pes;
    }
}
